package com.atzly.community.actuator;

import com.atzly.community.utils.CommunityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**  自定义actuator检查端点
 * @author zlysimida
 * @date 2021/9/5 - 13:17
 */
@Component
@Endpoint(id = "database")
@Slf4j
public class DatebaseEndpoint {

    @Autowired
    private DataSource dataSource;

    // 通过get请求进行访问
    @ReadOperation
    public String checkDatabaseConnection(){
        try (
                Connection connection = dataSource.getConnection();
                ) {
           return CommunityUtils.JsontoString(0,"获取数据库连接成功!");
        } catch (SQLException e) {
            log.error("获取数据库连接失败! err{}",e.getMessage());
            return CommunityUtils.JsontoString(1,"获取连接失败!");
        }
    }

}
